<template>
  <div>
    <div class="flex align-end">
      <el-avatar
        :src="defaultAvatar"
      />
      <!-- 上传头像按钮 -->
      <label style="line-height: 1;">
        <el-link
          class="font-mini ml-10"
          type="primary"
          :underline="false"
        >{{ $t('EDIT_AVATAR') }}</el-link>
        <input
          type="file"
          accept="image/*"
          :value="fileName"
          style="display: none"
          @change="selectFile"
        >
      </label>
    </div>
    <el-dialog
      :title="$t('EDIT_AVATAR')"
      :visible.sync="dialogVisible"
      :width="'700px'"
      append-to-body
      @close="handleClose"
    >
      <div class="flex justify-between">
        <vue-cropper
          ref="cropper"
          class="cropper-container"
          output-type="png"
          mode="cover"
          :fixed-box="true"
          :img="fileSrc"
          :output-size="1"
          :info="false"
          :full="true"
          :fixed="true"
          :can-move="false"
          :can-move-box="true"
          :original="false"
          :auto-crop="true"
          :auto-crop-width="180"
          :auto-crop-height="180"
          :high="true"
          :max-img-size="99999"
          @real-time="realTime"
        />
        <div class="flex-column align-center">
          <!-- 头像预览 -->
          <p>{{ $t('AVATAR_PREVIEW') }}</p>
          <div :style="previews.div" class="cropper-preview">
            <img :src="previews.url" :style="previews.img">
          </div>
          <!-- 放大、缩小、旋转按钮 -->
          <div>
            <el-button
              class="el-icon-plus el-icon-plus-change"
              @click="changeScale(1)"
            />
            <el-button class="el-icon-minus" @click="changeScale(-1)" />
            <el-button class="el-icon-refresh-right" @click="rotateRight" />
            <el-button class="el-icon-refresh-left" @click="rotateLeft" />
          </div>
        </div>
      </div>
      <div slot="footer">
        <el-button @click="handleClose">{{ $t('CANCEL') }}</el-button>
        <el-button type="primary" @click="uploadUserFile">{{
          $t('YES')
        }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { VueCropper } from 'vue-cropper'
  import userInfoApi from '@/api/basebiz/UserInfoApi'

  export default {
    components: {
      VueCropper
    },
    data() {
      return {
        dialogVisible: false,
        fileSrc: '',
        fileName: '',
        previews: {
          div: '',
          url: '',
          img: ''
        }
      }
    },
    computed: {
      ...mapGetters(['getUserId', 'avatarData']),
      defaultAvatar() {
        return this.avatarData ? this.avatarData.avatarData
          : require('@/assets/img/default_avatar.png')
      }
    },
    methods: {
      handleClose() {
        this.fileName = ''
        this.fileSrc = null
        this.dialogVisible = false
      },
      selectFile($event) {
        console.log('$event', $event)
        const file = $event.target.files[0]
        this.fileToUrl(file).then(url => {
          this.fileSrc = url
          this.dialogVisible = true
        })
      },
      fileToUrl(file) {
        return new Promise(resolve => {
          const fr = new FileReader()
          // 读取文件内容，读取完成,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容。
          fr.readAsDataURL(file)
          fr.onload = () => {
            // result属性为data:URL格式,与读取方式有关
            resolve(fr.result)
          }
        })
      },
      // 实时预览函数
      realTime(data) {
        this.previews = data
      },
      async uploadUserFile() {
        const imgData = await this.getFileByVueCropper()
        const res = await userInfoApi.saveUserInfo({
          id: this.avatarData ? this.avatarData.id : null,
          userId: this.getUserId,
          avatarData: imgData
        })
        if (res) {
          this.$store.dispatch('getAvatar')
          this.handleClose()
          this.$message.success(this.$t('MODIFY_SUCCESS'))
        } else {
          this.$message.error(this.$t('MODIFYFAILED'))
        }
      },
      getFileByVueCropper() {
        return new Promise(resolve => {
          this.$refs.cropper.getCropData(data => {
            resolve(data)
          })
        })
      },
      changeScale(num) {
        num = num || 1
        this.$refs.cropper.changeScale(num)
      },
      rotateLeft() {
        this.$refs.cropper.rotateLeft()
      },
      rotateRight() {
        this.$refs.cropper.rotateRight()
      }
    }
  }
</script>

<style lang="scss" scoped>
.vue-cropper.cropper-container {
  width: 400px;
  height: 400px;
}
.cropper-preview {
  margin: 20px 0;
  width: 180px;
  height: 180px;
  overflow: hidden;
  border: 1px solid #ccc;
  border-radius: 50%;
}
</style>
